Compiling and running a Java project from Windows command line.
Home
EXAMPLE 1
-----------
1. Simple java hello world HelloJar.jar file made from HelloJar.java:
---------------------------------------------------------------------
package helloJarPack;
public class HelloJar {
public static void printHelloFromJar(){
System.out.println("Hello from HelloJar.jar");
}
}
2. HelloUsingHelloJar.java file that references jar/library HelloJar.jar
----------------------------------------------------------------------------
import helloJarPack.HelloJar;
public class HelloUsingHelloJar {
public static void main(String[] args){
HelloJar.printHelloFromJar();
}
}
3. Folder structure and commands
------------------------------------
Only one folder is used, it contains HelloUsingHelloJar.java and HelloJar.jar.
Inside this folder open cmd prompt.
(inside folder hold shift and right click, select "Open Command Window Here")
javac -cp HelloJar.jar HelloUsingHelloJar.java (enter)
java -cp .;HelloJar.jar HelloUsingHelloJar (enter)
You should see "Hello from HelloJar.jar" printed in the console.
The first command creates the HelloUsingHelloJar.class file and puts it in the folder.
(-cp stands for class path)
EXAMPLE 2
------------
This example uses a more complex file structure staring with a root level folder
called FolderOne:
FolderOne
|
|--bin
|
|
|--lib
| |
| |--HelloJar.jar
|
|--src
|
|--helloPack
|
|--example
|
|--HelloUsingHelloJar.java
Inside this folder open cmd prompt and type this command then press enter:
javac -d bin -sourcepath src -cp .;lib/HelloJar.jar src/helloPack/example/HelloUsingHelloJar.java
(-d directs the file to the bin folder, if using Linux instead of windows replace ";" with ":")
This creates the HelloUsingHelloJar.class file and the file structure /helloPack/example/ and puts it in the bin folder.
Now the file tree should look like this:
FolderOne
|
|--bin
| |
| |--helloPack
| |
| |--example
| |
| |--HelloUsingHelloJar.class
|
|--lib
| |
| |--HelloJar.jar
|
|--src
|
|--helloPack
|
|--example
|
|--HelloUsingHelloJar.java
Now run this command:
java -cp bin;lib/HelloJar.jar helloPack.example.HelloUsingHelloJar
You should see "Hello from HelloJar.jar" printed in the console.